package com.mh.view;

import java.awt.Font;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import com.mh.entity.Book;
import com.mh.entity.BookType;
import com.mh.jdbc.entity.IPage;
import com.mh.jdbc.entity.MBean;
import com.mh.jdbc.util.StringUtil;
import com.mh.service.BookService;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.math.BigDecimal;

import javax.swing.ButtonGroup;

public class BookManage extends JInternalFrame {
	private BookService bookService = new BookService();
	private JTextField bookNameVal;
	private JTextField authorVal;
	private JComboBox bookTypeVal;
	private JButton searchBookBtn;
	private JButton provPage;
	private JButton nextPage;
	private JLabel currenPage;
	private JLabel totalPages;
	private JLabel bookrows;
	private JTable table;
	private JLabel lblNewLabel_2;
	private JTextField bookIdTxt;
	private JTextField bookNameTxt;
	private JTextField authorTxt;
	private JTextField priceTxt;
	private JTextArea bookDescTxt;
	private JRadioButton sex1,sex2;
	private JComboBox bookTypeSelect;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private int currentPage;
	/**
	 * Create the frame.
	 */
	public BookManage() {
		setClosable(true);
		setIconifiable(true);
		setTitle("图书管理");
		setBounds(100, 100, 800, 629);
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "\u641C\u7D22\u6761\u4EF6:", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JScrollPane scrollPane = new JScrollPane();
		
		provPage = new JButton("上一页");
		provPage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				IPage<Book> iPage = new IPage<>();
				iPage.setParmBean(new Book());
				iPage.setCurPage(StringUtil.getNum(currenPage.getText())-1);
				fillTable(iPage);
			}
		});
		
		nextPage = new JButton("下一页");
		nextPage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				IPage<Book> iPage = new IPage<>();
				iPage.setParmBean(new Book());
				iPage.setCurPage(StringUtil.getNum(currenPage.getText())+1);
				fillTable(iPage);
			}
		});
		
		currenPage = new JLabel("New label");
		
		totalPages = new JLabel("New label");
		
		bookrows = new JLabel("New label");
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "\u8868\u5355\u64CD\u4F5C", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(36)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 713, Short.MAX_VALUE)
						.addGroup(groupLayout.createSequentialGroup()
							.addComponent(provPage)
							.addGap(89)
							.addComponent(currenPage)
							.addPreferredGap(ComponentPlacement.RELATED, 93, Short.MAX_VALUE)
							.addComponent(totalPages)
							.addGap(95)
							.addComponent(bookrows)
							.addGap(77)
							.addComponent(nextPage))
						.addComponent(panel, GroupLayout.DEFAULT_SIZE, 713, Short.MAX_VALUE)
						.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 713, Short.MAX_VALUE))
					.addGap(35))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addComponent(panel, GroupLayout.PREFERRED_SIZE, 54, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 175, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(provPage)
						.addComponent(totalPages)
						.addComponent(nextPage)
						.addComponent(bookrows)
						.addComponent(currenPage))
					.addGap(34)
					.addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE)
					.addContainerGap())
		);
		
		lblNewLabel_2 = new JLabel("图书名称:");
		
		bookIdTxt = new JTextField();
		bookIdTxt.setColumns(10);
		
		JLabel lblNewLabel_3 = new JLabel("图书名称:");
		
		bookNameTxt = new JTextField();
		bookNameTxt.setColumns(10);
		
		JLabel lblNewLabel_4 = new JLabel("作者:");
		
		authorTxt = new JTextField();
		authorTxt.setColumns(10);
		
		JLabel lblNewLabel_5 = new JLabel("性别:");
		
		sex1 = new JRadioButton("男");
		buttonGroup.add(sex1);
		sex1.setSelected(true);
		
		sex2 = new JRadioButton("女");
		buttonGroup.add(sex2);
		
		JLabel lblNewLabel_6 = new JLabel("单价:");
		
		priceTxt = new JTextField();
		priceTxt.setColumns(10);
		
		JLabel lblNewLabel_7 = new JLabel("图书类型:");
		
		bookTypeSelect = new JComboBox();
		
		JLabel lblNewLabel_8 = new JLabel("图书描述:");
		
		bookDescTxt = new JTextArea();
		
		JButton editBtn = new JButton("修改");
		editBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Book book = new Book();
				book.setId(Integer.parseInt(bookIdTxt.getText()));
				String bookName = bookNameTxt.getText();
				if(StringUtil.isEmpty(bookName)){
					JOptionPane.showMessageDialog(null, "图书名称不能为空！");
					return;
				}
				book.setBookName(bookName);
				String author = authorTxt.getText();
				if(StringUtil.isEmpty(author)){
					JOptionPane.showMessageDialog(null, "作者姓名不能为空！");
					return;
				}
				book.setAuthor(author);
				try {
					BigDecimal price =new BigDecimal(priceTxt.getText());
					book.setPrice(price);
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(null, "图书价格输入格式不正确！");
					return;
				}
				int sex = 0;
				if(sex1.isSelected()){
					sex = 1;
				}else if(sex2.isSelected()){
					sex = 2;
				}
				book.setSex(sex);
				book.setBookType(((BookType)bookTypeSelect.getSelectedItem()).getId());
				book.setBookDesc(bookDescTxt.getText());
				if(bookService.modifyBook(book) > 0){
					JOptionPane.showMessageDialog(null, "图书信息修改成功！");
					IPage<Book> iPage = new IPage<>();
					iPage.setParmBean(book);
					iPage.setCurPage(currentPage);
					fillTable(iPage);
				}else{
					JOptionPane.showMessageDialog(null, "图书信息修改失败！");
				}
			}
		});
		editBtn.setIcon(new ImageIcon(BookManage.class.getResource("/com/mh/images/edit.png")));
		
		JButton deleteBtn = new JButton("删除");
		deleteBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int sts = JOptionPane.showConfirmDialog(null, "真的要删除这条记录吗？", "警告",JOptionPane.YES_NO_OPTION);
				if(sts == 0){
					Book book = new Book();
					book.setId(Integer.parseInt(bookIdTxt.getText()));
					if(bookService.deleteBook(book) > 0){
						JOptionPane.showMessageDialog(null, "图书信息删除成功！");
						IPage<Book> iPage = new IPage<>();
						iPage.setParmBean(book);
						iPage.setCurPage(currentPage);
						fillTable(iPage);
					}else{
						JOptionPane.showMessageDialog(null, "图书信息删除失败！");
					}
				}
			}
		});
		deleteBtn.setIcon(new ImageIcon(BookManage.class.getResource("/com/mh/images/delete.png")));
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel_1.createSequentialGroup()
							.addComponent(editBtn)
							.addPreferredGap(ComponentPlacement.RELATED, 488, Short.MAX_VALUE)
							.addComponent(deleteBtn))
						.addGroup(gl_panel_1.createSequentialGroup()
							.addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
								.addComponent(lblNewLabel_5)
								.addComponent(lblNewLabel_2))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING, false)
								.addGroup(gl_panel_1.createSequentialGroup()
									.addComponent(sex1)
									.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
									.addComponent(sex2))
								.addComponent(bookIdTxt, GroupLayout.PREFERRED_SIZE, 110, GroupLayout.PREFERRED_SIZE))
							.addGap(68)
							.addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
								.addComponent(lblNewLabel_6)
								.addComponent(lblNewLabel_3))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
								.addComponent(priceTxt, GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)
								.addComponent(bookNameTxt, GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING, false)
								.addGroup(gl_panel_1.createSequentialGroup()
									.addGap(53)
									.addComponent(lblNewLabel_4)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(authorTxt, GroupLayout.PREFERRED_SIZE, 123, GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_panel_1.createSequentialGroup()
									.addGap(26)
									.addComponent(lblNewLabel_7)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(bookTypeSelect, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
						.addGroup(gl_panel_1.createSequentialGroup()
							.addComponent(lblNewLabel_8)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(bookDescTxt, GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)))
					.addGap(25))
		);
		gl_panel_1.setVerticalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel_2)
						.addComponent(bookIdTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(authorTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNewLabel_4)
						.addComponent(bookNameTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNewLabel_3))
					.addGap(18)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
							.addComponent(lblNewLabel_5)
							.addComponent(sex1)
							.addComponent(sex2))
						.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
							.addComponent(lblNewLabel_6)
							.addComponent(priceTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
							.addComponent(bookTypeSelect, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
							.addComponent(lblNewLabel_7)))
					.addGap(18)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel_8)
						.addComponent(bookDescTxt, GroupLayout.PREFERRED_SIZE, 65, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(editBtn)
						.addComponent(deleteBtn))
					.addContainerGap())
		);
		panel_1.setLayout(gl_panel_1);
		
		table = new JTable();
		table.setFont(new Font("宋体", Font.PLAIN, 16));
		table.setRowHeight(21);
		table.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				bookTableMousePressed(e);
			}
		});
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u7F16\u53F7", "\u56FE\u4E66\u540D\u79F0", "\u4F5C\u8005", "\u6027\u522B", "\u5355\u4EF7", "\u7C7B\u578B", "\u56FE\u4E66\u63CF\u8FF0"
			}
		));
		table.getColumnModel().getColumn(5).setPreferredWidth(115);
		table.getColumnModel().getColumn(6).setPreferredWidth(283);
		scrollPane.setViewportView(table);
		
		JLabel lblNewLabel = new JLabel("图书名称:");
		
		bookNameVal = new JTextField();
		bookNameVal.setColumns(10);
		
		JLabel lblNewLabel_1 = new JLabel("图书作者:");
		
		authorVal = new JTextField();
		authorVal.setColumns(10);
		
		bookTypeVal = new JComboBox();
		
		searchBookBtn = new JButton("搜索");
		searchBookBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Book book = new Book();
				book.setBookName(bookNameVal.getText());
				book.setAuthor(authorVal.getName());
				int bookId = ((BookType)bookTypeVal.getSelectedItem()).getId();
				if(bookId != -1) book.setBookType(bookId);
				clearBookTypeForm();
				IPage<Book> iPage = new IPage<>();
				iPage.setParmBean(book);
				fillTable(iPage);
			}
		});
		searchBookBtn.setFont(new Font("宋体", Font.PLAIN, 14));
		searchBookBtn.setIcon(new ImageIcon(BookManage.class.getResource("/com/mh/images/search.png")));
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addGap(29)
					.addComponent(lblNewLabel)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(bookNameVal, GroupLayout.PREFERRED_SIZE, 94, GroupLayout.PREFERRED_SIZE)
					.addGap(27)
					.addComponent(lblNewLabel_1)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(authorVal, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addGap(38)
					.addComponent(bookTypeVal, GroupLayout.PREFERRED_SIZE, 154, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
					.addComponent(searchBookBtn))
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel)
						.addComponent(bookNameVal, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(authorVal, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNewLabel_1)
						.addComponent(bookTypeVal, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(searchBookBtn))
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		panel.setLayout(gl_panel);
		getContentPane().setLayout(groupLayout);
		bookIdTxt.setEditable(false);
		this.fillBookType();
		IPage<Book> iPage = new IPage<>();
		iPage.setParmBean(new Book());
		this.fillTable(iPage);
	}
	protected void bookTableMousePressed(MouseEvent env) {
		int row = this.table.getSelectedRow();
		bookIdTxt.setText(table.getValueAt(row, 0).toString());
		bookNameTxt.setText(table.getValueAt(row, 1).toString());
		authorTxt.setText(table.getValueAt(row, 2).toString());
		String sex = table.getValueAt(row, 3).toString();
		if("男".equals(sex)){
			sex1.setSelected(true);
		}else if("女".equals(sex)){
			sex2.setSelected(true);
		}
		priceTxt.setText(table.getValueAt(row, 4).toString());
		this.fillBookTypeForm(table.getValueAt(row, 5).toString());
		bookDescTxt.setText(table.getValueAt(row, 6).toString());
	}
	private void clearBookTypeForm(){
		bookIdTxt.setText("");
		bookNameTxt.setText("");
		authorTxt.setText("");
		priceTxt.setText("");
		this.fillBookTypeForm("");
		bookDescTxt.setText("");
	}
	private void fillBookTypeForm(String bookTypeName){
		List<BookType> bookTypeList = bookService.findBookType();
		for(int i=0,len = bookTypeList.size();i<len;i++){
			BookType bokType = bookTypeList.get(i);
			bookTypeSelect.addItem(bokType);
			if(bookTypeName.equals(bokType.getBookTypeName()))
			bookTypeSelect.setSelectedIndex(i);
		}
	}
	private void fillTable(IPage<Book> iPage){
		//初始化按钮
		provPage.setEnabled(true);
		nextPage.setEnabled(true);
		DefaultTableModel dtm = (DefaultTableModel) table.getModel();
		dtm.setRowCount(0);
		IPage<Book> iPageDB = bookService.findBook(iPage);
		int curPage = iPageDB.getCurPage();
		int totalpage = iPageDB.getTotalpage();
		currenPage.setText("当前页:"+curPage);
		totalPages.setText("总页数:"+totalpage);
		bookrows.setText(String.format("总记录数%s条", iPageDB.getRows()));
		if(curPage == 1) provPage.setEnabled(false);
		if(curPage+1 > totalpage) nextPage.setEnabled(false);
		currentPage = curPage;
		for(MBean mBean : iPageDB.getResult()){
			Book book= (Book) mBean;
			Vector<Object> vector = new  Vector<>();
			vector.add(book.getId());
			vector.add(book.getBookName());
			vector.add(book.getAuthor());
			vector.add(book.getSex() == 1 ? "男" : "女");
			vector.add(Double.parseDouble(book.getPrice().toString()));
			vector.add(bookService.findBookById(book.getBookType()));
			vector.add(book.getBookDesc());
			dtm.addRow(vector);
		};
	}
	/**
	 * 初始化图书类别
	 */
	private void fillBookType(){
		Iterator<BookType> item = bookService.findBookType().iterator();
		bookTypeVal.addItem(new BookType(-1,"--请选择--"));
		while(item.hasNext()){
			bookTypeVal.addItem(item.next());
		}
	}
}
